from rest_framework import serializers
from .models import (
    Notice, Active, BgPic, Bill, Comment,
    Enotice, LostFound, User, Property,
    Repair, Staff, SearchRecord, ActivityRegistration, PropertyUserRelation
)


class NoticeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Notice
        fields = '__all__'


class ActiveSerializer(serializers.ModelSerializer):
    categoryDisplay = serializers.SerializerMethodField()
    username = serializers.SerializerMethodField()
    userInfo = serializers.SerializerMethodField()

    class Meta:
        model = Active
        fields = [
            'id', 'cover', 'category', 'categoryDisplay', 'title',
            'ac_description', 'userId', 'username',  # 加了 username
            'browseCount', 'location', 'description','userInfo'
        ]

    def get_categoryDisplay(self, obj):
        return obj.get_category_display()

    def get_username(self, obj):
        return obj.userId.username if obj.userId else None

    def get_userInfo(self, obj):
        if obj.userId:
            return UserSerializer(obj.userId).data
        return None



class BgPicSerializer(serializers.ModelSerializer):
    class Meta:
        model = BgPic
        fields = '__all__'


class BillSerializer(serializers.ModelSerializer):
    catagoryDisplay = serializers.SerializerMethodField()
    username = serializers.SerializerMethodField()

    class Meta:
        model = Bill
        fields = [
            'id', 'userId', 'username', 'catagory', 'catagoryDisplay', 'amount',
            'paid', 'description', 'billtime'
        ]

    def get_catagoryDisplay(self, obj):
        return obj.get_catagory_display()  # 获取账单类别的中文翻译

    def get_username(self, obj):
        return obj.userId.username if obj.userId else None  # 获取用户的用户名


class CommentSerializer(serializers.ModelSerializer):
    # 翻译字段
    username = serializers.SerializerMethodField()  # 显示用户名
    activeTitle = serializers.SerializerMethodField()  # 显示活动标题

    class Meta:
        model = Comment
        fields = ['id', 'username','userId', 'content', 'activeTitle','activesId']  # 序列化的字段

    def get_username(self, obj):
        # 获取用户名，如果 userId 存在
        return obj.userId.username if obj.userId else None

    def get_activeTitle(self, obj):
        # 获取活动标题，如果 activesId 存在
        return obj.activesId.title if obj.activesId else None


class EnoticeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Enotice
        fields = '__all__'


class LostFoundSerializer(serializers.ModelSerializer):
    class Meta:
        model = LostFound
        fields = '__all__'


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'email', 'tel', 'location', 'age', 'gender', 'avatar']
        extra_kwargs = {
            'password': {'write_only': True},
        }

    def create(self, validated_data):
        # 创建用户时使用 set_password 来加密密码
        user = User(
            username=validated_data['username'],
            email=validated_data.get('email'),
            tel=validated_data.get('tel'),
            location=validated_data.get('location'),
            age=validated_data.get('age'),
            gender=validated_data.get('gender'),
            avatar=validated_data.get('avatar'),
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

    def update(self, instance, validated_data):
        # 修改密码时进行加密
        if 'password' in validated_data:
            instance.set_password(validated_data.pop('password'))
        return super().update(instance, validated_data)


class PropertySerializer(serializers.ModelSerializer):
    typeDisplay = serializers.SerializerMethodField()
    username = serializers.SerializerMethodField()

    class Meta:
        model = Property
        fields = [
            'id', 'floor', 'userId', 'username', 'type', 'typeDisplay',
            'address', 'area', 'layout'
        ]

    def get_typeDisplay(self, obj):
        return obj.get_type_display()  # 正确方法名：get_<字段名>_display()

    def get_username(self, obj):
        return obj.userId.username if obj.userId else None


class RepairSerializer(serializers.ModelSerializer):
    typeDisplay = serializers.SerializerMethodField()
    statusDisplay = serializers.SerializerMethodField()
    username = serializers.SerializerMethodField()

    class Meta:
        model = Repair
        fields = [
            'id', 'userId', 'username', 'time', 'type', 'typeDisplay',
            'problem', 'status', 'statusDisplay', 'handleResult'
        ]

    def get_typeDisplay(self, obj):
        return obj.get_type_display()  # 获取维修类型的中文翻译

    def get_statusDisplay(self, obj):
        return obj.get_status_display()  # 获取处理状态的中文翻译

    def get_username(self, obj):
        return obj.userId.username if obj.userId else None  # 获取报修人员的用户名


class StaffSerializer(serializers.ModelSerializer):
    class Meta:
        model = Staff
        fields = '__all__'

class SearchRecordSerializer(serializers.ModelSerializer):
    class Meta:
        model = SearchRecord
        fields = '__all__'

class ActivityRegistrationSerializer(serializers.ModelSerializer):
    class Meta:
        model = ActivityRegistration
        fields = '__all__'



class PropertyUserRelationSerializer(serializers.ModelSerializer):
    staff = StaffSerializer(source='staffId', read_only=True)

    class Meta:
        model = PropertyUserRelation
        fields = ('id', 'userId','staffId','staff')  # 只列出需要的字段
